package com.manage.func.article.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.manage.base.bean.CommonResultBean;
import com.manage.base.controller.BaseController;
import com.manage.config.model.Config;
import com.manage.config.service.IConfigService;
import com.manage.func.article.model.ArticleBean;
import com.manage.func.article.model.ArticleCatalogBean;
import com.manage.func.article.model.ArticleCommentBean;
import com.manage.func.article.service.IArticleService;
import com.manage.user.model.User;
import com.manage.util.KeyValueHelper;
import com.manage.util.StringUtil;
import com.manage.util.SystemUtil;

/**
 * 新闻管理
 * 
 * @author ouyangyf
 *
 */
@Controller
@RequestMapping("/article")
public class ArticleController extends BaseController {

	private static final long serialVersionUID = 1L;

	static final Logger LOG = LoggerFactory.getLogger(ArticleController.class);

	@Autowired
	private IArticleService articleService;
	@Autowired
	private IConfigService iConfigService;

	// 查询新闻
	@RequestMapping(value = "select", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean select(@RequestParam("data") String data) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("article select called: " + data);
			ArticleBean bean = fromJson(data, ArticleBean.class);
			bean = convertSearchTime(bean);
			if (bean != null) {
				List<ArticleBean> beans = articleService.selectArticleList(bean);
				beans = convertHttp(beans);
				int size = articleService.selectTotalCount(bean);
				sys.put("articles", beans);
				sys.put("size", size);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	// 查询新闻分类
	@RequestMapping(value = "catalog/select", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean catalogSelect(@RequestParam("data") String data) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("article catalog select called: " + data);
			List<ArticleCatalogBean> beans = articleService.selectArticleCatalogList();
			sys.put("catalogs", beans);
			return sys;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	private ArticleBean convertSearchTime(ArticleBean param) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			if (StringUtil.notEmpty(param.createTimeStringStart)) {
				param.createTimeStart = new Timestamp(sdf.parse(param.createTimeStringStart).getTime());
			} else {
				param.createTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.createTimeStringEnd)) {
				param.createTimeEnd = new Timestamp(sdf.parse(param.createTimeStringEnd).getTime());
			} else {
				param.createTimeStringEnd = null;
			}

			if (StringUtil.notEmpty(param.updateTimeStringStart)) {
				param.updateTimeStart = new Timestamp(sdf.parse(param.updateTimeStringStart).getTime());
			} else {
				param.updateTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.updateTimeStringEnd)) {
				param.updateTimeEnd = new Timestamp(sdf.parse(param.updateTimeStringEnd).getTime());
			} else {
				param.updateTimeStringEnd = null;
			}

			if (StringUtil.notEmpty(param.expireTimeStringStart)) {
				param.expireTimeStart = new Timestamp(sdf.parse(param.expireTimeStringStart).getTime());
			} else {
				param.expireTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.expireTimeStringEnd)) {
				param.expireTimeEnd = new Timestamp(sdf.parse(param.expireTimeStringEnd).getTime());
			} else {
				param.expireTimeStringEnd = null;
			}

			if (StringUtil.notEmpty(param.catalog)) {
				if (param.catalog.equals("全部")) {
					param.catalog = null;
				}
			}
		} catch (ParseException e) {
			LOG.error(e.getMessage(), e);
		}
		return param;
	}

	/**
	 * 转换URL
	 * 
	 * @param articleBeans
	 *            /images/article/1463026911636859951.jpg
	 */
	protected List<ArticleBean> convertHttp(List<ArticleBean> articleBeans) {
		String context = SystemUtil.getAppProp("image_context");
		for (ArticleBean bean : articleBeans) {
			if (StringUtil.notEmpty(bean.httpPath)) {
				bean.httpPath = "http://" + context + bean.httpPath;
			}
			if (StringUtil.notEmpty(bean.previewPicture)) {
				bean.previewPicture = "http://" + context + bean.previewPicture;
			}
			if (StringUtil.notEmpty(bean.headlineImage)) {
				bean.headlineImage = "http://" + context + bean.headlineImage;
			}
			if (StringUtil.notEmpty(bean.homePageImage)) {
				bean.homePageImage = "http://" + context + bean.homePageImage;
			}
		}
		return articleBeans;
	}

	private ArticleBean convertAddTime(ArticleBean param) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			if (StringUtil.notEmpty(param.expireTime)) {
				param.expireTimeDb = new Timestamp(sdf.parse(param.expireTime).getTime());
			}
		} catch (ParseException e) {
			LOG.error(e.getMessage(), e);
		}
		return param;
	}

	private ArticleBean convertImagePath(ArticleBean param) {
		try {
			if (StringUtil.notEmpty(param.previewPicture)) {
				String str = param.previewPicture.split(Config.ARTTICLE_IMAGE_HTTP)[1];
				param.previewPicture = Config.ARTTICLE_IMAGE_HTTP + str;
			}

			if (StringUtil.notEmpty(param.homePageImage)) {
				String str = param.homePageImage.split(Config.ARTTICLE_IMAGE_HTTP)[1];
				param.homePageImage = Config.ARTTICLE_IMAGE_HTTP + str;
			}

			if (StringUtil.notEmpty(param.headlineImage)) {
				String str = param.headlineImage.split(Config.ARTTICLE_IMAGE_HTTP)[1];
				param.headlineImage = Config.ARTTICLE_IMAGE_HTTP + str;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return param;
	}

	/**
	 * 图片上传
	 * 
	 * @param uploadFile
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/image/upload")
	@ResponseBody
	public CommonResultBean pictureUpload(
			@RequestParam(value = "uploadFile", required = false) MultipartFile uploadFile,
			HttpServletRequest request) {
		if (uploadFile == null || uploadFile.getOriginalFilename().trim().equals("")) {
			CommonResultBean commonResultBean = new CommonResultBean();
			commonResultBean.setResult_code(Config.FAILE);
			commonResultBean.setResult_message("图片为空，上传失败");
			return commonResultBean;
		} else {
			try {
				String rootPath = super.getWebRootPath(request);
				String rootUrl = super.getWebRootUrl(request);
				String fileFullName = saveImage(uploadFile, rootPath, rootUrl);
				CommonResultBean commonResultBean = new CommonResultBean();
				commonResultBean.setResult_code(Config.SUCCESS);
				commonResultBean.setResult_message("主图片上传成功");
				Map<String, Object> result_map = new HashMap<String, Object>();
				result_map.put("url", fileFullName);
				commonResultBean.setResult_map(result_map);
				return commonResultBean;

			} catch (Exception e) {
				e.printStackTrace();
				CommonResultBean commonResultBean = new CommonResultBean();
				commonResultBean.setResult_code(Config.FAILE);
				commonResultBean.setResult_message("主图片上传异常");
				return commonResultBean;
			}

		}
	}

	private String saveImage(MultipartFile uploadFile, String rootPath, String rootUrl) {
		try {
			// 未完成，调试再弄
			String httpUrl = Config.HTTP_TITLE + SystemUtil.getAppProp("image_context");
			String suffix = uploadFile.getOriginalFilename()
					.substring(uploadFile.getOriginalFilename().lastIndexOf("."));
			String prePath = rootPath + Config.ARTTICLE_IMAGE_PATH;
			String filePath = System.currentTimeMillis() + getFixLenthString(6) + suffix;
			String returnPath = httpUrl + Config.ARTTICLE_IMAGE_HTTP + filePath;
			String savePath = prePath + filePath;
			File preDir = new File(prePath);
			if (!preDir.exists()) {
				preDir.mkdirs();
			}
			uploadFile.transferTo(new File(savePath));
			return returnPath;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}

	private String saveFile(ArticleBean bean, String rootPath, String rootUrl) {
		try {
			ArticleBean beandb = articleService.selectArticleById(bean);

			if (null == beandb || null == beandb.getHttpPath() || "".equals(beandb.getHttpPath())) {
				String httpUrl = Config.HTTP_TITLE + SystemUtil.getAppProp("image_context");
				String prePath = rootPath + Config.ARTTICLE_FILE_PATH;
				String filePath = System.currentTimeMillis() + getFixLenthString(6) + ".html";
				String httpPath = httpUrl + Config.ARTTICLE_FILE_HTTP + filePath;
				String dbPath = Config.ARTTICLE_FILE_HTTP + filePath;
				String savePath = prePath + filePath;
				File preDir = new File(prePath);
				if (!preDir.exists()) {
					preDir.mkdirs();
				}
				writerHtml(savePath, bean.content);
				bean.filePath = savePath;
				bean.httpPath = dbPath;
				return httpPath;
			} else {
				String dbPath = beandb.getHttpPath();
				String httpUrl = Config.HTTP_TITLE + SystemUtil.getAppProp("image_context");
				String prePath = rootPath + Config.ARTTICLE_FILE_PATH;
				String httpPath = httpUrl + dbPath;
				String savePath = rootPath + dbPath;
				File preDir = new File(prePath);
				if (!preDir.exists()) {
					preDir.mkdirs();
				}

				File deleteFile = new File(savePath);
				if (deleteFile.exists()) {
					deleteFile.delete();
				}
				writerHtml(savePath, bean.content);
				bean.filePath = savePath;
				bean.httpPath = dbPath;
				return httpPath;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}

	// 写文件
	private void writerHtml(String path, String content) {
		BufferedWriter fw = null;
		try {
			File file = new File(path);
			fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true),
					SystemUtil.getProp("articile_encoding", "utf-8"))); // 指定编码格式，以免读取时中文字符异常
			fw.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
			String css = SystemUtil.getProp("cssposition", "/carfee/styles/formatat.css");
			fw.append("<link href=\"" + css + "\" type=\"text/css\" rel=\"stylesheet\"></link>");
			fw.write(content);
			// video_fullscreen
			fw.append(KeyValueHelper.get("video_fullscreen"));
			fw.flush(); // 全部写入缓存中的内容
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static String getFixLenthString(int strLength) {

		Random rm = new Random();
		// 获得随机数
		double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
		// 将获得的获得随机数转化为字符串
		String fixLenthString = String.valueOf(pross);
		// 返回固定的长度的随机数
		return fixLenthString.substring(1, strLength + 1);
	}

	// 添加新闻
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean add(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		String rootPath = super.getWebRootPath(request);
		String rootUrl = super.getWebRootUrl(request);
		try {
			LOG.info("article add called: " + data);

			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ArticleBean bean = fromJson(data, ArticleBean.class);

			if (!checkHomePageTotalCountAdd(bean)) {
				sys.setErrorMsg("轮播图片数量已经达到上限，不能再进行添加");
				return sys;
			}

			if (!checkHeadLineTotalCountAdd(bean)) {
				sys.setErrorMsg("新闻头条图片数量已经达到上限，不能再进行添加");
				return sys;
			}

			bean.adminId = sysuser.getUserId();
			bean = convertAddTime(bean);
			bean = convertImagePath(bean);
			saveFile(bean, rootPath, rootUrl);
			if (bean != null) {
				articleService.insertArticle(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	private boolean checkHomePageTotalCountAdd(ArticleBean bean) {

		KeyValueHelper.load(iConfigService.selectKeyValueList());
		String db_count = KeyValueHelper.get("homepage_total_count");
		int config_count = 5;
		if (null != db_count || !"".equals(db_count)) {
			config_count = Integer.valueOf(db_count);
		}
		int current_count = iConfigService.selectHomePageTotalCount();
		if (bean.getIsHomePage() == 0) {
			return true;
		}
		if (current_count < config_count && bean.getIsHomePage() == 1) {
			return true;
		}
		return false;
	}

	private boolean checkHeadLineTotalCountAdd(ArticleBean bean) {

		KeyValueHelper.load(iConfigService.selectKeyValueList());
		String db_count = KeyValueHelper.get("headline_total_count");
		int config_count = 1;
		if (null != db_count || !"".equals(db_count)) {
			config_count = Integer.valueOf(db_count);
		}
		int current_count = iConfigService.selectHeadLineTotalCount();

		if (bean.getIsHeadline() == 0) {
			return true;
		}
		if (current_count < config_count && bean.getIsHeadline() == 1) {
			return true;
		}
		return false;
	}

	// 添加新闻
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean update(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		String rootPath = super.getWebRootPath(request);
		String rootUrl = super.getWebRootUrl(request);
		try {
			LOG.info("article add called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ArticleBean bean = fromJson(data, ArticleBean.class);

			if (!checkHomePageTotalCountUpdate(bean)) {
				sys.setErrorMsg("轮播图片数量已经达到上限，不能再进行添加");
				return sys;
			}

			if (!checkHeadLineTotalCountUpdate(bean)) {
				sys.setErrorMsg("头条图片数量已经达到上限，不能再进行添加");
				return sys;
			}

			bean.adminId = sysuser.getUserId();
			bean = convertAddTime(bean);
			bean = convertImagePath(bean);
			saveFile(bean, rootPath, rootUrl);
			if (bean != null) {
				articleService.updateArticle(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	private boolean checkHomePageTotalCountUpdate(ArticleBean bean) {
		int current_count = iConfigService.selectHomePageTotalCount();

		KeyValueHelper.load(iConfigService.selectKeyValueList());
		int oldHomePageFlag = articleService.selectArticleById(bean).getIsHomePage();

		String db_count = KeyValueHelper.get("homepage_total_count");
		int config_count = 5;
		if (null != db_count || !"".equals(db_count)) {
			config_count = Integer.valueOf(db_count);
		}

		if (bean.getIsHomePage() == 0) {
			return true;
		}

		if (oldHomePageFlag == 1) {
			return true;
		} else {
			if (current_count < config_count && bean.getIsHomePage() == 1) {
				return true;
			}
			return false;
		}
	}

	private boolean checkHeadLineTotalCountUpdate(ArticleBean bean) {
		int current_count = iConfigService.selectHeadLineTotalCount();
		KeyValueHelper.load(iConfigService.selectKeyValueList());
		int oldHeadLineFlag = articleService.selectArticleById(bean).getIsHeadline();

		String db_count = KeyValueHelper.get("headline_total_count");
		int config_count = 1;
		if (null != db_count || !"".equals(db_count)) {
			config_count = Integer.valueOf(db_count);
		}
		if (bean.getIsHeadline() == 0) {
			return true;
		}
		if (oldHeadLineFlag == 1) {
			return true;
		} else {
			if (current_count < config_count || bean.getIsHeadline() == 0) {
				return true;
			}
			return false;
		}
	}

	// 删除新闻
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean delete(@RequestParam("data") String data) {
		LOG.info("article delete: " + data);
		CommonResultBean sys = new CommonResultBean();
		try {
			ArticleBean bean = fromJson(data, ArticleBean.class);
			// int i = 
			articleService.deleteArticle(bean);
			sys.setResult_code(Config.SUCCESS);
			sys.setResult_message(Config.SUCCESS_MSG);
			return sys;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	// 查询新闻评论
	@RequestMapping(value = "comment/select", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean commentSelect(@RequestParam("data") String data) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("article comment select called: " + data);
			ArticleCommentBean bean = fromJson(data, ArticleCommentBean.class);
			bean = convertCommentSearchTime(bean);
			if (bean != null) {
				List<ArticleCommentBean> beans = articleService.selectArticleCommentListById(bean);
				int size = articleService.selectArticleCommentCountById(bean);
				sys.put("articles", beans);
				sys.put("size", size);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	private ArticleCommentBean convertCommentSearchTime(ArticleCommentBean param) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			if (StringUtil.notEmpty(param.createTimeStringStart)) {
				param.createTimeStart = new Timestamp(sdf.parse(param.createTimeStringStart).getTime());
			} else {
				param.createTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.createTimeStringEnd)) {
				param.createTimeEnd = new Timestamp(sdf.parse(param.createTimeStringEnd).getTime());
			} else {
				param.createTimeStringEnd = null;
			}

			if (StringUtil.notEmpty(param.updateTimeStringStart)) {
				param.updateTimeStart = new Timestamp(sdf.parse(param.updateTimeStringStart).getTime());
			} else {
				param.updateTimeStringStart = null;
			}

			if (StringUtil.notEmpty(param.updateTimeStringEnd)) {
				param.updateTimeEnd = new Timestamp(sdf.parse(param.updateTimeStringEnd).getTime());
			} else {
				param.updateTimeStringEnd = null;
			}

		} catch (ParseException e) {
			LOG.error(e.getMessage(), e);
		}
		return param;
	}

	// 更新评论状态
	@RequestMapping(value = "comment/update", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean updateCommentStatus(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("comment update called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ArticleCommentBean bean = fromJson(data, ArticleCommentBean.class);
			bean.adminId = sysuser.getUserId();
			if (bean != null) {
				articleService.updateCommentStatus(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	// 更新评论状态
	@RequestMapping(value = "comment/delete", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean delCommont(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("delCommont called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ArticleCommentBean bean = fromJson(data, ArticleCommentBean.class);
			bean.adminId = sysuser.getUserId();
			if (bean != null) {
				articleService.delCommont(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	// 更新评论状态
	@RequestMapping(value = "comment/deleteTotal", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean delTotalCommont(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("delTotalCommont called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ArticleCommentBean bean = fromJson(data, ArticleCommentBean.class);
			bean.adminId = sysuser.getUserId();
			if (bean != null) {
				articleService.deleteTotalComment(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}
}
